/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 *
 * @see You can view component api by: https://github.com/ant-design/ant-design-pro-layout
 */
import type {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import type { Dispatch } from 'umi';
import { Link, useIntl, connect, history } from 'umi';
import { Result, Button, message } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import type { ConnectState } from '@/models/connect';
import { getMatchMenu } from '@umijs/route-utils';
import logo from '../assets/oplug.svg';
import moment from 'moment';

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);
export type BasicLayoutProps = {
  breadcrumbNameMap: Record<string, MenuDataItem>;
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
  menuData: MenuDataItem[];
  loading: boolean;
  currentConfig: any;
  currentTenant: any;
} & ProLayoutProps;
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: Record<string, MenuDataItem>;
};
/** Use Authorized check all menu item */

const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList?.map((item) => {
    const localItem = {
      ...item,
      children: item.children ? menuDataRender(item.children) : undefined,
      path: item.path ? item.path : '/',
    };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem; //item.authority
  });

const routeRender = (menuList: any[], route: any): any[] =>
  menuList?.map((item) => {
    const localItem = {
      routes: item.children ? routeRender(item.children, route) : undefined,
      component: item.component,
      path: item.path ? item.path : '/',
    };
    route.routes.push(item.path);
    return localItem;
  });

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
    menuData,
    loading,
    currentConfig,
  } = props;

  const menuDataRef = useRef<MenuDataItem[]>([]);
  const [configData, setConfig] = useState<any>({});
  const [tenantData, setTenant] = useState<any>({});

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      }).then(() => {
        setTenant(props.currentTenant);
        if (props.currentTenant.endDate) {
          var startTime = new Date(Date.parse(new Date().toLocaleDateString())).getTime();
          var endTime = new Date(Date.parse(moment(props.currentTenant.endDate).format('YYYY-MM-DD'))).getTime();
          var dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24);
          if (dates <= 20) {
            message.warning('产品试用期剩余' + dates.toFixed(0) + '天');
          }
        }
      });

      dispatch({
        type: 'AbpMenu/fetchMenu',
      });

      dispatch({
        type: 'user/fetchConfig',
      }).then(() => {
        setConfig(props.currentConfig);
      });
    }
  }, []);
  /** Init variables */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };
  // get children authority
  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );

  const { formatMessage } = useIntl();
  //const myRoute = routeRender(menuData,route);

  const defaultFooterDom = (
    <DefaultFooter
      copyright={`${new Date().getFullYear()} ` + `${currentConfig.companyName ? currentConfig.companyName : 'OPERP'}` + ` ${tenantData.name?tenantData.name:'-'}` + ` 有效期至${tenantData.endDate ? moment(tenantData.endDate).format('YYYY-MM-DD') : '无限期'} `}
      links={
        [
          // {
          //   key: 'Ant Design Pro',
          //   title: 'Ant Design Pro',
          //   href: 'https://pro.ant.design',
          //   blankTarget: true,
          // },
          // {
          //   key: 'github',
          //   title: <GithubOutlined />,
          //   href: 'https://github.com/ant-design/ant-design-pro',
          //   blankTarget: true,
          // },
          // {
          //   key: 'Ant Design',
          //   title: 'Ant Design',
          //   href: 'https://ant.design',
          //   blankTarget: true,
          // },
        ]
      }
    />
  );
  var firstMenu = {
    path: '/welcome',
    name: 'welcome',
    icon: 'icon-planner',
    component: './Welcome',
  };
  var menuDataIn = menuDataRender(menuData);
  if(menuDataIn){
    menuDataIn.unshift(firstMenu);
  }  
  return (
    <ProLayout
      logo={logo}
      formatMessage={formatMessage}
      {...props}
      {...settings}
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (
          menuItemProps.isUrl ||
          !menuItemProps.path ||
          location.pathname === menuItemProps.path
        ) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({ id: 'menu.home' }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      footerRender={() => {
        if (settings.footerRender || settings.footerRender === undefined) {
          return defaultFooterDom;
        }
        return null;
      }}
      menuDataRender={() => menuDataIn}
      //menuDataRender={menuDataRender}
      menu={{
        loading,
      }}
      rightContentRender={() => <RightContent />}
      postMenuData={(menuData) => {
        menuDataRef.current = menuData || [];
        return menuData || [];
      }}
      waterMarkProps={{
        content: 'OPERP',
        fontColor: 'rgba(24,144,255,0.15)',
      }}
    //route={() => myRoute}
    >
      <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );
};

export default connect(({ global, settings, AbpMenu, user }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  menuData: AbpMenu.menuData,
  loading: AbpMenu.loading,
  currentUser: user.currentUser,
  currentConfig: user.currentConfig,
  currentTenant: user.currentTenant,
}))(BasicLayout);
